<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-13 15:07:16
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-06-09
-->
<template>
  <div>
    <LayoutPanel class="private-common-wrapper" title="$t('thirdPart.source')">
      <!-- 
        :scroll="{ y: 500, x: 1000 }" -->
      <!-- <rj-table
        :columns="thirdPartColumns"
        :dataSource="thirdParts"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          selectedRows: selectedRows,
          onChange: onSelectChange,
        }"
        :pagination="pagination"
        :loading="isTableLoading"
        rowKey="id"
        filtercolumns
        @refeshTable="getSourceList"
        @change="handleTableChange"
      >
        <div slot="customBlock" class="log-opt-wrapper">
          <rj-space :size="16">
            <a-button class="icon-btn" type="primary" @click="onAdd">
              <icon-font type="ic-plus" />
              {{ $t('thirdPart.addSource') }}
            </a-button>
            <a-button @click="onDelete(null)">
              {{ $t('common.batchDelete') }}
            </a-button>
          </rj-space>
          <a-input-search
            class="w-200"
            :placeholder="$t('thirdPart.sourceName')"
            v-model="queryParamObj.name"
            @change="filterSearch"
          />
        </div>

        <template slot="sourceType" slot-scope="text">
          {{ getSourceType(text) }}
        </template>

        <template slot="sourceProfile" slot-scope="text, record">
          <div class="policy-item-wrapper">
            <div
              class="policy-item"
              :key="policyItem.uuid"
              v-for="policyItem in getAuthPolicyItems(record)"
              :class="policyItem.type"
            >
              <icon-font type="ic-yewufangwenkongzhi2" />
              {{ policyItem.name }}
            </div>
          </div>
        </template>

        <template slot="action" slot-scope="text, record">
          <rj-space :size="16">
            <icon-font type="ic-edit" @click="onEdit(record)" />
            <icon-font type="ic-delete" @click="onDelete(record)" />
          </rj-space>
        </template>
      </rj-table> -->

      <ThirdPartEditor
        :record="firstRecord"
        @refreshList="getSourceList"
        ref="editorRef"
      />
    </LayoutPanel>
    <!-- <ThirdPartCreator @refreshList="getSourceList" ref="creatorRef" /> -->
  </div>
</template>

<script>
import { RjTable } from '@components';
// import ThirdPartCreator from './thirdPartCreator/index';
import ThirdPartEditor from './thirdPartEditor/index.vue';
import { requestHttp, maccApi } from '@utils/index';
import LayoutPanel from '@views/common/deviceDetail/components/components/layoutPanel.vue';
import { thirdPartColumns } from './columns.js';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import { mapState } from 'vuex';
import lodash from 'lodash';

export default {
  name: 'thirdPart',
  mixins: [authSysMixin],
  components: {
    ThirdPartEditor,
    // ThirdPartCreator,
    // 'rj-table': RjTable,
    LayoutPanel,
  },
  data() {
    return {
      thirdPartColumns,
      isMoreVisible: false,
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100'],
        total: 0,
        current: 1,
        pageSize: 10,
      },
      filterObj: {
        account: '',
        email: '',
        note: '',
        deadlineTime: null,
        createTimes: null,
        accountStatus: '',
      },
      thirdParts: [],
      selectedRowKeys: [],
      selectedRows: [],
      isTable: false,
      queryParamObj: {
        name: '',
      },
      statusCount: {},
      batchModalShow: false,
      macModalShow: false,
      uuid: '',
      isTableVisible: true,
      isTableLoading: false,
      firstRecord: {
        accountSourceProfileList: [],
      }, // tommy 24.6.3 第一条记录
    };
  },
  async mounted() {
    await this.getAuthPolicyList();
    this.getSourceList();
  },
  computed: {
    ...mapState('AuthCommon', ['authPolicys']),

    authPolicyMap() {
      const policyMap = {};
      this.authPolicys.forEach((policy) => {
        policyMap[policy.uuid] = policy.name;
      });
      return policyMap;
    },
  },
  methods: {
    getAuthPolicyItems(record) {
      const policyItems = [];
      if (this.authPolicyMap[record.defaultProfileId]) {
        policyItems.push({
          type: 'default',
          uuid: record.defaultProfileId,
          name: this.authPolicyMap[record.defaultProfileId],
        });
      }
      if (record.accountSourceProfileIdList) {
        for (const profileId of record.accountSourceProfileIdList) {
          if (this.authPolicyMap[profileId]) {
            policyItems.push({
              type: 'normal',
              uuid: profileId,
              name: this.authPolicyMap[profileId],
            });
          }
        }
      }
      return policyItems;
    },
    async getAuthPolicyList() {
      const res = await this.requestHttpAuth({
        api: maccApi.MACC_PROFILE_GET_API,
        method: 'GET',
        replaces: {
          tenantName: this.tenantInfo.tenantName,
          groupId: this.groupId,
        },
        querys: {
          tenantId: this.tenantInfo.tenantId,
          start: 0,
          pageSize: 100,
        },
      });
      if (res.data.code === 0) {
        this.$store.commit(
          'AuthCommon/SET_AUTH_POLICY_LIST',
          res?.data?.list || []
        );
      } else {
        this.$message.warning(res.data.msg);
      }
    },
    getSourceType(txt) {
      switch (txt) {
        case 'ad':
          return this.$t('thirdPart.adArea');
        case 'ldap':
          return 'LDAP';
        default:
      }
    },
    async onShowMore() {
      this.isMoreVisible = !this.isMoreVisible;
    },
    filterSearch() {
      this.pagination.current = 1;
      this.getSourceList();
    },
    openBatchModal() {
      this.batchModalShow = true;
    },
    handleTableChange(pagination, filterObj) {
      this.pagination = pagination;
      this.filterObj = filterObj;
      this.thirdPartColumns.find(
        (item) => item.dataIndex == 'type'
      ).filteredValue = this.filterObj.type || null;
      this.getSourceList();
    },
    // 查询数据
    async getSourceList() {
      const res = await this.requestHttpAuth({
        api: maccApi.MACC_SOURCE_GET_API,
        replaces: {
          tenantName: this.tenantInfo.tenantName,
          groupId: this.groupId,
        },
        querys: {
          tenantId: this.tenantInfo.tenantId,
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          name: this.queryParamObj.name,
        },
        method: 'GET',
      });

      this.selectedRowKeys = [];
      this.isTableLoading = false;
      if (res.data.success) {
        this.pagination.total = res?.data?.result?.total || 0;
        this.thirdParts = res?.data?.result?.items || [];

        if (this.thirdParts.length > 0) {
          // this.firstRecord = await this.getSouceDetail(this.thirdParts[0].id);
          this.firstRecord = {
            ...this.thirdParts[0],
            accountSourceProfileList: [],
          };
          this.getSouceDetail(this.firstRecord);
        }
      } else {
        this.$message.warning(res.data.message);
      }
    },

    /**
     * @description: tommy 240609 暂时用不到
     * @param {*} record
     * @return {*}
     */
    async onEdit(record) {
      // const recordDetail = await this.getSouceDetail(record.id);
      const recordDetail = record;
      if (!recordDetail) {
        return false;
      }

      const tempRecord = lodash.cloneDeep(record);
      tempRecord.accountSourceProfileList =
        recordDetail.accountSourceProfileList;

      this.isTableVisible = false;
      this.$refs.editorRef.openEditor(tempRecord);
    },

    /**
     * @description: 为了直接保存要请求
     * @param {*} id
     * @return {*}
     */
    async getSouceDetail(record) {
      const res = await this.requestHttpAuth({
        api: maccApi.MACC_SOURCE_DETAIL_GET_API,
        method: 'GET',
        querys: {
          id: record.id,
        },
      });

      if (res.data.success) {
        // return res.data.result;
        const accountSourceProfileList =
          res.data.result?.accountSourceProfileList || [];
        record.accountSourceProfileList = accountSourceProfileList;
      } else {
        this.$message.warning(res.data.message);
      }
    },

    onAdd() {
      this.isTableVisible = false;
      this.$refs.creatorRef.openEditor();
    },
    closeEditor() {
      this.isTableVisible = true;

      this.$refs.editorRef.closeEditor();
    },
    // 表格复选框勾选事件
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 删除账号
    onDelete(row) {
      if (!row) {
        if (!this.selectedRowKeys.length) {
          this.$message.warning(this.$t('userManage.selectOneAccount'));
          return;
        }
      }
      this.$confirm({
        title: this.$t('userManage.message'),
        content: this.$t('userManage.deleteRecord'),
        onOk: async () => {
          let idStr = '';
          if (row) {
            idStr = row.id;
          } else {
            const ids = this.selectedRows.map((item) => item.id);
            idStr = ids.join(',');
          }
          const res = await this.requestHttpAuth({
            api: maccApi.MACC_SOURCE_BATCH_DEL_API,
            method: 'DELETE',
            querys: {
              ids: idStr,
            },
          });
          if (res.data.success) {
            this.$message.success(this.$t('common.delSuccess'));
            this.getSourceList();
          } else {
            this.$message.warning(res.data.message);
          }
        },
      });
    },
  },
};
</script>

<style scoped lang="less">
.private-common-wrapper {
  /deep/.layout-panel-head {
    display: none !important;
  }
  padding: 16px;
  .title {
    display: flex;
    justify-content: space-between;
  }
}
.table-adv-content {
  padding: 12px;
  background: @bg-component;
  border-radius: 4px;
  margin-bottom: 12px;
  text-align: left;
  display: flex;
  gap: 16px 40px;
  flex-wrap: wrap;
  .adv-search-item {
    display: inline-block;
    & > label {
      width: 180px;
      display: inline-block;
      padding-right: 16px;
      text-align: right;
    }
    & > span {
      width: 320px !important;
    }
    & > input {
      width: 320px;
    }
    &.btn-item {
      display: flex;
      gap: 16px;
      margin-left: auto;
    }
  }
}
.log-opt-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}
.icon-btn {
  i {
    font-size: 15px;
    padding-top: 3px;
  }
}
.mtb-20 {
  margin: 20px 0px;
}
.w-200 {
  width: 200px;
}
.policy-item-wrapper {
  display: flex;
  gap: 8px;
}
.policy-item {
  border-radius: 2px;
  height: 30px;
  line-height: 30px;
  padding: 0 6px;
  display: flex;
  align-items: center;
  gap: 3px;
  i {
    font-size: 18px;
  }
  &.default {
    background: @success-light;
    color: @success-color;
    border: 1px solid @success-focus;
  }
  &.normal {
    background: @theme-light;
    color: @theme-color;
    border: 1px solid @theme-focus;
  }
}
</style>
